import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import avatarRoutes from './routes/avatar.js';
import uploadRoutes from './routes/upload.js';
import { errorHandler } from './middleware/errorHandler.js';

// 加载环境变量
dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express();
const PORT = process.env.PORT || 3001;

// 配置 CORS，允许前端从任何端口访问
app.use(cors({
  origin: function (origin, callback) {
    // 允许所有 localhost 端口
    if (!origin || origin.startsWith('http://localhost:')) {
      callback(null, true);
    } else {
      callback(null, true); // 开发环境允许所有源
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// 设置编码和请求体解析
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 设置响应头，确保中文正确显示
app.use((req, res, next) => {
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  next();
});

// 静态文件服务
app.use('/uploads', express.static(join(__dirname, 'uploads')));
app.use('/images', express.static(join(__dirname, 'images')));

// API 路由
app.use('/api/avatar', avatarRoutes);
app.use('/api/upload', uploadRoutes);

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'Avatar Generator Backend is running',
    timestamp: new Date().toISOString(),
    port: PORT
  });
});

// 错误处理中间件
app.use(errorHandler);

// 404 处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    error: {
      message: '接口不存在',
      statusCode: 404,
      path: req.originalUrl
    }
  });
});

app.listen(PORT, () => {
  console.log(`🚀 Avatar Generator Backend running on port ${PORT}`);
  console.log(`🔗 Health check: http://localhost:${PORT}/health`);
  console.log(`🌐 CORS enabled for all localhost ports`);
});
